/*
* 设备维修上报
* */

import 'package:center_beijing/api/task_api.dart';
import 'package:center_beijing/common/QRScan.dart';
import 'package:center_beijing/common/styles.dart';
import 'package:center_beijing/config/routeConfig.dart';
import 'package:center_beijing/widgets/custom_input_widget.dart';
import 'package:center_beijing/widgets/custom_loading_widget.dart';
import 'package:center_beijing/widgets/selectRow_widget.dart';
import 'package:center_beijing/widgets/textarea_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_pickers/time_picker/model/date_mode.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'dart:io';
import 'package:get/get.dart';
import 'dart:convert';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:left_scroll_actions/cupertinoLeftScroll.dart';
import 'package:left_scroll_actions/global/actionListener.dart';

class EquipmentMaintenanceReport extends StatefulWidget {
  @override
  _EquipmentMaintenanceReportState createState() =>
      _EquipmentMaintenanceReportState();
}

class _EquipmentMaintenanceReportState
    extends State<EquipmentMaintenanceReport> {
  CustomLoading loading = CustomLoading.withMessage('保存中...');
  var repairUnit = TextEditingController();
  var repairType = TextEditingController();
  var repairPerson = TextEditingController(); //主修人
  var testPerson = TextEditingController(); //检验人
  var pickUpPeron = TextEditingController(); //接机人
  List selectList = [];
  List selectPart = [];
  var enterDate = '';
  var outDate = '';
  var technicalStatus = '';
  var afterRepair = '';

/*
  * 提交
  * */
  submit() async {
    loading.show(delay: 20);
    var pass = {
      'item': json.encode({
        'machineId': selectList[0]['id'],
        'repairComp': repairUnit.text,
        'repairType': repairType.text,
        'approachDate': enterDate,
        'outDate': outDate,
        'contentBefore': technicalStatus,
        'questionAfter': afterRepair,
        'repairUserId': repairPerson.text,
        'checkUserId': testPerson.text,
        'acceptUserId': pickUpPeron.text,
        'partDetails': this.selectPart
      }),
    };
    var result = await saveMachineRepair(pass);
    loading.dismiss();
    if (result != null) {
      Fluttertoast.showToast(msg: '保存完成');
      Get.back();
    }
  }

  getEquipmentDetail(compId) async {
    var pass = {'id': compId};
    var result = await getEquipmentInfo(pass);
    if (result != null && result['errorMessage'] == null) {
      selectList = [];
      this.setState(() {
        selectList.add(result);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('设备维修'),
        ),
        body: SafeArea(
          child: Container(
            padding: EdgeInsets.only(
                bottom: MediaQuery.of(context).padding.bottom + 70),
            child: SingleChildScrollView(
              child: Column(
                children: [
                  Container(
                    padding: EdgeInsets.fromLTRB(
                        Styles.spacing16, 0, Styles.spacing16, 0),
                    margin: EdgeInsets.fromLTRB(
                        0, Styles.spacing8, 0, Styles.spacing8),
                    child: Row(
                      children: [
                        Expanded(
                          child: GestureDetector(
                            onTap: () async {
                              var result = await Get.toNamed(
                                  RouteConfig.selectEquipment);
                              if (result != null) {
                                selectList = [];
                                selectList.add(result);
                                this.setState(() {});
                              }
                            },
                            child: Container(
                              alignment: Alignment.center,
                              padding: EdgeInsets.fromLTRB(
                                  Styles.spacing16,
                                  Styles.spacing8,
                                  Styles.spacing16,
                                  Styles.spacing8),
                              decoration: BoxDecoration(
                                  color: Styles.GrayLight,
                                  border: Border.all(
                                      color: Styles.LineColor, width: 1),
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(4.0.r))),
                              child: Text(
                                '搜索/手动选择设备',
                                style: TextStyle(
                                    color: Styles.LeftTitleColor,
                                    fontSize: Styles.NormalFont),
                              ),
                            ),
                          ),
                        ),
                        GestureDetector(
                          onTap: () async {
                            var result = await QrScan.scan(context, type: 2);
                            if (result != null) {
                              this.getEquipmentDetail(result['code']);
                            }
                          },
                          child: Container(
                            color: Styles.BlueColor,
                            padding: EdgeInsets.fromLTRB(
                                Styles.spacing8,
                                Styles.spacing8,
                                Styles.spacing8,
                                Styles.spacing8),
                            margin: EdgeInsets.only(left: Styles.spacing16),
                            child: Image.asset(
                              'assets/images/scan.png',
                              width: 20.w,
                              height: 20.h,
                              fit: BoxFit.contain,
                              color: Colors.white,
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                  Column(
                    children: this.selectList.map((item) {
                      return CupertinoLeftScroll(
                        // important, each Row must have different key.
                        // DO NOT use '$index' as Key! Use id or title.
                        key: Key(item.toString()),
                        // left scroll widget will auto close while the other widget is opened and has same closeTag.
                        // 当另一个有相同closeTag的组件打开时，其他有着相同closeTag的组件会自动关闭.
                        closeTag: LeftScrollCloseTag(item.toString()),
                        buttonWidth: 80,
                        child: Container(
                          color: Colors.white,
                          padding: EdgeInsets.fromLTRB(
                              Styles.spacing8,
                              Styles.spacing8,
                              Styles.spacing8,
                              Styles.spacing8),
                          margin: EdgeInsets.only(top: Styles.spacing8),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                children: [
                                  Container(
                                    margin:
                                        EdgeInsets.only(right: Styles.spacing8),
                                    height: 20.h,
                                    width: 4.w,
                                    color: Styles.BlueColor,
                                  ),
                                  Text(
                                    item['name'] != null
                                        ? item['name']
                                        : (item['equipmentName'] != null
                                            ? item['equipmentName']
                                            : '--'),
                                    style: TextStyle(
                                        color: Styles.DetailColor,
                                        fontSize: Styles.Middle16Font),
                                  ),
                                ],
                              ),
                              Container(
                                margin: EdgeInsets.fromLTRB(Styles.spacing8,
                                    Styles.spacing8, Styles.spacing8, 0),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      (item['attr'] != null &&
                                              item['attr']['modelType'] != null)
                                          ? item['attr']['modelType']
                                          : (item['modelType'] != null
                                              ? item['modelType']
                                              : '--'),
                                      style: TextStyle(
                                          color: Styles.DetailColor,
                                          fontSize: Styles.Middle16Font),
                                    ),
                                    Text(
                                      (item['attr'] != null &&
                                              item['attr']['address'] != null)
                                          ? item['attr']['address']
                                          : (item['address'] != null
                                              ? item['address']
                                              : '--'),
                                      style: TextStyle(
                                          color: Styles.LeftTitleColor,
                                          fontSize: Styles.NormalFont),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                        buttons: <Widget>[
                          GestureDetector(
                            onTap: () {
                              print('删除');
                            },
                            child: Container(
                              margin: EdgeInsets.fromLTRB(
                                  0, 0, Styles.spacing16, 0),
                              decoration: BoxDecoration(
                                color: Styles.RedColor,
                                borderRadius:
                                    BorderRadius.all(Radius.circular(14.0.r)),
                              ),
                              alignment: Alignment.center,
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Image(
                                    image:
                                        AssetImage('assets/images/delete.png'),
                                    width: 16.w,
                                    height: 16.w,
                                    fit: BoxFit.contain,
                                  ),
                                  Text(
                                    '删除',
                                    style: TextStyle(
                                        color: Colors.white,
                                        fontSize: Styles.NormalFont),
                                  )
                                ],
                              ),
                            ),
                          ),
                        ],
                        onTap: () {
                          print('tap row');
                        },
                      );
                    }).toList(),
                  ),
                  Container(
                    margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                    padding: EdgeInsets.fromLTRB(
                        Styles.spacing8, 0, Styles.spacing8, 0),
                    child: CustomInput(
                      textAlign: TextAlign.left,
                      inputformat: [
                        LengthLimitingTextInputFormatter(10),
                      ],
                      title: '承修单位',
                      placeHold: '请输入',
                      textInput: this.repairUnit,
                      clearAll: false,
                      require: false,
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                    padding: EdgeInsets.fromLTRB(
                        Styles.spacing8, 0, Styles.spacing8, 0),
                    child: CustomInput(
                      textAlign: TextAlign.left,
                      inputformat: [
                        LengthLimitingTextInputFormatter(10),
                      ],
                      title: '修理类别',
                      placeHold: '请输入',
                      textInput: this.repairType,
                      clearAll: false,
                      require: false,
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                    color: Colors.white,
                    padding: EdgeInsets.fromLTRB(Styles.spacing8, 0, 0, 0),
                    child: SelectRow(
                        titleFont: Styles.MiddleFont17,
                        require: false,
                        selectType: DateMode.YMD,
                        title: '进厂日期',
                        rightText: enterDate,
                        selectCallback: (value) {
                          this.setState(() {
                            enterDate = value;
                          });
                        }),
                  ),
                  Container(
                    margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                    color: Colors.white,
                    padding: EdgeInsets.fromLTRB(Styles.spacing8, 0, 0, 0),
                    child: SelectRow(
                        titleFont: Styles.MiddleFont17,
                        require: false,
                        selectType: DateMode.YMD,
                        title: '出厂日期',
                        rightText: outDate,
                        selectCallback: (value) {
                          this.setState(() {
                            outDate = value;
                          });
                        }),
                  ),
                  Container(
                    color: Colors.white,
                    margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                    padding: EdgeInsets.fromLTRB(
                        Styles.spacing8, 0, Styles.spacing8, 0),
                    child: TextAreaWidget(
                      maxLength: 100,
                      labelText: '修前技术状况',
                      defaultValue: '',
                      placeholder: '请输入',
                      disabled: false,
                      required: false,
                      rows: 4,
                      onChange: (value) => this.setState(() {
                        technicalStatus = value;
                      }),
                    ),
                  ),
                  Container(
                    color: Colors.white,
                    margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                    padding: EdgeInsets.fromLTRB(
                        Styles.spacing8, 0, Styles.spacing8, 0),
                    child: TextAreaWidget(
                      maxLength: 100,
                      labelText: '修后尚存问题',
                      defaultValue: '',
                      placeholder: '请输入',
                      disabled: false,
                      required: false,
                      rows: 4,
                      onChange: (value) => this.setState(() {
                        afterRepair = value;
                      }),
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                    padding: EdgeInsets.fromLTRB(
                        Styles.spacing8, 0, Styles.spacing8, 0),
                    child: CustomInput(
                      textAlign: TextAlign.left,
                      inputformat: [
                        LengthLimitingTextInputFormatter(10),
                      ],
                      title: '主修人',
                      placeHold: '请输入',
                      textInput: this.repairPerson,
                      clearAll: false,
                      require: false,
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                    padding: EdgeInsets.fromLTRB(
                        Styles.spacing8, 0, Styles.spacing8, 0),
                    child: CustomInput(
                      textAlign: TextAlign.left,
                      inputformat: [
                        LengthLimitingTextInputFormatter(10),
                      ],
                      title: '检验人',
                      placeHold: '请输入',
                      textInput: this.testPerson,
                      clearAll: false,
                      require: false,
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                    padding: EdgeInsets.fromLTRB(
                        Styles.spacing8, 0, Styles.spacing8, 0),
                    child: CustomInput(
                      textAlign: TextAlign.left,
                      inputformat: [
                        LengthLimitingTextInputFormatter(10),
                      ],
                      title: '接机人',
                      placeHold: '请输入',
                      textInput: this.pickUpPeron,
                      clearAll: false,
                      require: false,
                    ),
                  ),
                  GestureDetector(
                    behavior: HitTestBehavior.translucent,
                    onTap: () async {
                    var result =  await Get.toNamed(RouteConfig.addEquipmentPart);
                      if(result!=null){
                        this.selectPart.add(result);
                        this.setState(() {

                        });
                      }
                    },
                    child: Container(
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                          border:
                              Border.all(color: Styles.BlueColor, width: 1)),
                      padding: EdgeInsets.fromLTRB(Styles.spacing8,
                          Styles.spacing12, Styles.spacing8, Styles.spacing12),
                      margin: EdgeInsets.fromLTRB(Styles.spacing16,
                          Styles.spacing16, Styles.spacing16, 0),
                      child: Text(
                        '添加零件配件',
                        style: TextStyle(
                            color: Styles.BlueColor,
                            fontSize: Styles.NormalFont),
                      ),
                    ),
                  ),
                  Column(
                    children: this.selectPart.map((item) {
                      return CupertinoLeftScroll(
                        // important, each Row must have different key.
                        // DO NOT use '$index' as Key! Use id or title.
                        key: Key(item.toString()),
                        // left scroll widget will auto close while the other widget is opened and has same closeTag.
                        // 当另一个有相同closeTag的组件打开时，其他有着相同closeTag的组件会自动关闭.
                        closeTag: LeftScrollCloseTag(item.toString()),
                        buttonWidth: 80,
                        child: Container(
                          color: Colors.white,
                          padding: EdgeInsets.fromLTRB(
                              Styles.spacing8,
                              Styles.spacing8,
                              Styles.spacing8,
                              Styles.spacing8),
                          margin: EdgeInsets.only(top: Styles.spacing8),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                children: [
                                  Container(
                                    margin:
                                    EdgeInsets.only(right: Styles.spacing8),
                                    height: 20.h,
                                    width: 4.w,
                                    color: Styles.BlueColor,
                                  ),
                                  Text(
                                    "${item['partName']} (${item['partNum']}${item['partUnit']}) ",
                                    style: TextStyle(
                                        color: Styles.DetailColor,
                                        fontSize: Styles.Middle16Font),
                                  ),
                                ],
                              ),
                              Container(
                                margin: EdgeInsets.fromLTRB(Styles.spacing8,
                                    Styles.spacing8, Styles.spacing8, 0),
                                child: Text(
                                  '规格 ${item['partType']}',
                                  style: TextStyle(
                                      color: Styles.DetailColor,
                                      fontSize: Styles.Middle16Font),
                                ),
                              ),
                              Container(
                                margin: EdgeInsets.fromLTRB(Styles.spacing8,
                                    Styles.spacing8, Styles.spacing8, 0),
                                child: Text(
                                  '备注 ${item['remark']}',
                                  style: TextStyle(
                                      color: Styles.DetailColor,
                                      fontSize: Styles.Middle16Font),
                                ),
                              ),
                            ],
                          ),
                        ),
                        buttons: <Widget>[
                          GestureDetector(
                            onTap: () {
                              print('删除');
                              this.selectPart.remove(item);
                              this.setState(() {

                              });
                            },
                            child: Container(
                              margin: EdgeInsets.fromLTRB(
                                  0, 0, Styles.spacing16, 0),
                              decoration: BoxDecoration(
                                color: Styles.RedColor,
                                borderRadius:
                                BorderRadius.all(Radius.circular(14.0.r)),
                              ),
                              alignment: Alignment.center,
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Image(
                                    image:
                                    AssetImage('assets/images/delete.png'),
                                    width: 16.w,
                                    height: 16.w,
                                    fit: BoxFit.contain,
                                  ),
                                  Text(
                                    '删除',
                                    style: TextStyle(
                                        color: Colors.white,
                                        fontSize: Styles.NormalFont),
                                  )
                                ],
                              ),
                            ),
                          ),
                        ],
                        onTap: () {
                          print('tap row');
                        },
                      );
                    }).toList(),
                  ),
                ],
              ),
            ),
          ),
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
        floatingActionButton: Container(
          padding: EdgeInsets.fromLTRB(
              Styles.spacing8, Styles.spacing8, Styles.spacing8, 10),
          child: Container(
            decoration: new BoxDecoration(
              //背景
              color: Styles.BlueColor,
              //设置四周圆角 角度
              borderRadius: BorderRadius.all(Radius.circular(12.0)),
            ),
            child: FlatButton(
              disabledColor: Styles.SelectColor,
              onPressed: () {
                if(this.selectList.isEmpty){
                  Fluttertoast.showToast(msg: "请选择设备");
                }else{
                  this.submit();
                }

              },
              child: Container(
                height: Styles.MainButtonHeight,
                alignment: Alignment.center,
                child: Text(
                  '保存',
                  style: TextStyle(
                      fontSize: Styles.MainButtonTextFont, color: Colors.white),
                ),
              ),
            ),
          ),
        ));
  }
}
